import 'dart:convert';
import 'package:FlutterApp/City.dart';
import 'package:http/http.dart' as http;
import 'package:FlutterApp/Weather.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class WeatherWidget extends StatefulWidget {
  City city;

  WeatherWidget({this.city});

  @override
  WeatherWidgetState createState() => new WeatherWidgetState(city: this.city);
}

class WeatherWidgetState extends State<WeatherWidget> {
  Weather weather = Weather.empty();
  City city;

  WeatherWidgetState({this.city}) {
    getData();
  }

  void getData() async {
    Weather data = await postRequest();
    setState(() {
      weather = data;
    });
  }

  //  发起网络请求
  Future<Weather> postRequest() async {
    // https://www.sojson.com/open/api/weather/json.shtml?city=北京
    final response = await http.get('http://t.weather.sojson.com/api/weather/city/' + this.city.id);
    if(response.statusCode == 200){
      return Weather.fromJson(json.decode(response.body));
    }else{
      return Weather.empty();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              Image.asset("image/img-city.jpg",
                  fit: BoxFit.cover
              ),
              Container(
                child: Column(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(top: 30),
                      child:  Text(this.city.name,
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 25
                          )
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 160),
                      child: Text(weather?.tmp,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 50
                        ),),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(0, 5, 0, 5),
                      child: Text(weather?.cond,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 30
                        ),),
                    ),
                    Container(
                      child: Text(weather?.hum,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 15
                        ),),
                    )
                  ],
                ),
              )
            ],
          )
      ),
    );
  }
}